package org.qf.service;

import com.alibaba.druid.util.StringUtils;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.qf.mapper.RoleMapper;
import org.qf.mapper.UserMapper;

import org.qf.pojo.Role;
import org.qf.pojo.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import tk.mybatis.mapper.entity.Example;

import javax.annotation.Resource;
import java.util.List;

@Service
public class UserService {
    @Resource
    public UserMapper userMapper;
    @Resource
    public RoleMapper roleMapper ;

    public User login(String username, String password) {
        User user=new User();
        user.setUsername(username);
        user.setUserpassword(password);
        User user1 = userMapper.selectOne(user);
        return user1;
    }

    public int register(User user) {

        return userMapper.insert(user);
    }

    //查询功能并分页
    public PageInfo<User> showUser(int pageNum,String name){

        //当前页 页面容量
        PageHelper.startPage(pageNum,3);
        Example example=new Example(User.class);
        Example.Criteria criteria=example.createCriteria();

        if(!StringUtils.isEmpty(name)) {
            //通过用户名进行模糊查询
            criteria.andLike("username", '%' + name + '%');
        }
        List<User> Users =userMapper.selectByExample(example);
        System.out.println(Users);
//        List<User> Users = userMapper.selectAll();
        List<Role> roles = roleMapper.selectAll();

        //可以得到用户对象中的userRole
        //那么角色表中的id就可以赋值了
//        bindUser(Users);
        for (User user: Users) {
            for (Role role:roles) {
                if (user.getUserrole().equals(role.getId()))
                {
                    user.setUserrole(role.getRolename());
                }
            }
            // user.getAge();
            System.out.println("=========" + user.getAge());
        }
        PageInfo<User> pageInfo=new PageInfo<User>(Users);
        return pageInfo;
    }

    public int addUser(User user) {
        return  userMapper.insertSelective(user);
    }

    public User selectByID(String id) {
        return userMapper.selectByPrimaryKey(id);
    }

    public int EditUser(User user) {
        return userMapper.updateByPrimaryKeySelective(user);
    }

    public int DeleteUser(User user) {
        return userMapper.deleteByPrimaryKey(user.getId());
    }

    public int editPassword(User user) {
        return userMapper.updateByPrimaryKeySelective(user);
    }
}
